<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('common.id')">
        <el-input
          v-model="form.id"
          :clearable="true"
          :placeholder="t('common.inputText') + t('common.id')"
          style="width: 250px"
        />
      </el-form-item>

      <el-form-item :label="t('inventory.cname')">
        <el-select
          v-model="form.product_id"
          :placeholder="t('common.inputText') + t('inventory.cname')"
          :filterable="true"
          :multiple="true"
          :remote="true"
          :remote-method="getProductOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.cname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('warehouse.name')">
        <el-select
          v-model="form.warehouse_id"
          :placeholder="t('common.inputText') + t('warehouse.name')"
          :filterable="true"
          :multiple="true"
          :remote="true"
          :remote-method="getWarehouseOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 新增 库存类型 搜索 -->
      <el-form-item :label="t('inventory.is_futures')">
        <el-select
          :clearable="true"
          v-model="form.is_futures"
          :placeholder="t('inventory.is_futures')"
          style="width: 250px"
        >
          <el-option
            v-for="item in isFuturesList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('wholesalOrder.orderNo')">
        <el-input
          v-model="form.order_no"
          clearable
          :placeholder="t('wholesalOrder.orderNo')"
          style="width: 250px"
        />
      </el-form-item>

      <el-form-item :label="t('dealerAssetManagement.dealers')">
        <el-select
          v-model="form.user_id"
          :placeholder="
            t('common.inputText') +
            ' ' +
            t('dealerAssetManagement.dealers') +
            ' ' +
            t('dealerAssetManagement.nameOrEmail')
          "
          :filterable="true"
          :multiple="true"
          :clearable="true"
          :remote="true"
          :remote-method="getCustomerOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in distributorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.status')">
        <el-select
          v-model="form.status"
          :placeholder="t('wholesalOrder.status')"
          :clearable="true"
          :multiple="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.payStatus')">
        <el-select
          v-model="form.pay_status"
          :placeholder="t('wholesalOrder.payStatus')"
          :clearable="true"
          :multiple="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in payStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.exceptionstatus')">
        <el-select
          :clearable="true"
          v-model="form.exceptionstatus"
          :multiple="true"
          :placeholder="t('order.exceptionstatus')"
          style="width: 250px"
        >
          <el-option
            v-for="item in exceptionStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.aftersales_status')">
        <el-select
          v-model="form.aftersales_status"
          :placeholder="t('order.aftersales_status')"
          :clearable="true"
          :multiple="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in afterSalesStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.create_time')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          @change="changeTime"
          :editable="false"
          unlink-panels
          :clearable="true"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">{{
          t('common.query')
        }}</el-button>
        <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleJump('add')">
        {{ t('system.marketChannel.add') }}
      </el-button>
      <!--      <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatch('delete')">-->
      <!--        {{ t('system.marketChannel.batchDelete') }}-->
      <!--      </el-button>-->
    </div>
    <!-- 表格主体 -->
    <Table
      :data="dataList"
      :columns="tableColumns"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      showAction
      @selection-change="handleSelectionChange"
    />
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
  <!--  选择客户弹框-->
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    :multiple="true"
    @expose-multiple-data="getExposeCustomerData"
  />

  <!--      上传支付审核弹框-->
  <DialogUpload ref="DialogUploadRef" @refresh="initialize" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import DialogCustomerChecked from './components/DialogCustomerChecked/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker, useEnumerateMultiplePicker } from '@/utils'
import { getEnumApi, getListApi } from '@/api/wholesalOrder'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSelectApi as getCustomerSelectApi } from '@/api/customer'
import { getListApi as getProductListApi } from '@/api/product'
import DialogUpload from '@/views/Order/WholesalOrder/components/DialogUpload/index.vue'
import { Table } from '@/components/Table'
import { useWholesalOrderTableColumns } from './components/hooks/useTableColumns'
import { getListApi as getWarehouseListApi } from '@/api/warehouse'

const { t } = useI18n()
const { push } = useRouter()
const DialogCustomerCheckedRef = ref()
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const customerCheckedList = ref<Array<Record<string, any>>>([])
const DialogUploadRef = ref<InstanceType<typeof DialogUpload>>()
const selectLoading = ref<boolean>(false)

const paginationTotal = ref<number>(0)
const customerName = ref<string>()
const form = ref<Record<string, any>>({
  id: '',
  order_no: '',
  user_id: [],
  // user_ids: [],
  status: '',
  pay_status: '',
  date: [],
  start_time: '',
  end_time: '',
  pageIndex: 1,
  pageSize: 30,
  is_futures: '',
  aftersales_status: ''
})

const currencyList = ref<Array<Record<string, any>>>([])
const payStatusList = ref<Array<Record<string, any>>>([])
const paymentMethodList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])
const distributorList = ref<Array<Record<string, any>>>([])
const signatoryList = ref<Array<Record<string, any>>>([])
const contractSigningStatusList = ref<Array<Record<string, any>>>([])
const singleOrderMethodList = ref<Array<Record<string, any>>>([])
const payTermsList = ref<Array<Record<string, any>>>([]) // 支付条款
const exceptionStatusList = ref<Array<Record<string, any>>>([])
const isFuturesList = ref<Array<Record<string, any>>>([])
const afterSalesStatusList = ref<Array<Record<string, any>>>([])

// 客户异步下拉框
const getCustomerOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const distributorResp = await getCustomerSelectApi({ role: 'distributor', cusname: value })
    distributorList.value = distributorResp.data
    selectLoading.value = false
  }
}

//仓库异步下拉框
const warehouseList = ref<Array<Record<string, any>>>([])
const getWarehouseOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const warehouseResp = await getWarehouseListApi({ name: value })
    warehouseList.value = warehouseResp.data.list
    console.log(666, warehouseList.value)
    selectLoading.value = false
  }
}
//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  customerCheckedList.value = val
  customerName.value = val.map((item: Record<string, any>) => item.email).join(',')
  form.value.user_ids = val.map((item: Record<string, any>) => item.id)
}
//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const handleJump = (type: string, row?: Record<string, any>) => {
  const path = ref<string>('') // 默认值为空字符串
  const query = reactive<{ [key: string]: string }>({}) // 默认值为空字符串
  switch (type) {
    case 'customer':
      path.value = `/customer/customerList/detail`
      query.id = row?.user_id
      query.source = `/order/order-management`
      break
    default:
      path.value = `/order/wholesal-order-management/${type}`
      query.id = row?.id
      break
  }

  push({ path: path.value, query })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  statusList.value = resp.data.status
  payStatusList.value = resp.data.pay_status
  paymentMethodList.value = resp.data.pay_method
  currencyList.value = resp.data.currency
  signatoryList.value = resp.data.operator
  contractSigningStatusList.value = resp.data.contract_signing_status
  singleOrderMethodList.value = resp.data.single_order_method
  payTermsList.value = resp.data.pay_terms
  exceptionStatusList.value = resp.data.exceptionstatus
  isFuturesList.value = resp.data.is_futures || []
  afterSalesStatusList.value = resp.data.aftersales_status || []
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    order_no: '',
    user_id: [],
    // user_ids: [],
    status: '',
    pay_status: '',
    date: [],
    start_time: '',
    end_time: '',
    pageIndex: 1,
    pageSize: 30,
    is_futures: '',
    aftersales_status: ''
  }
  paginationTotal.value = 0
  customerCheckedList.value = []
  customerName.value = ''
  form.value.user_ids = []
  initialize()
}

onActivated(() => {
  getDropDownBoxInfo()
  initialize()
})

// 产品异步下拉框
const productList = ref<Array<Record<string, any>>>([])
const getProductOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const productResp = await getProductListApi({ cname: value })
    productList.value = productResp.data.list
    console.log(666, productList.value)
    selectLoading.value = false
  }
}
const tableColumns = useWholesalOrderTableColumns(
  handleJump,
  useEnumeratePicker,
  useEnumerateMultiplePicker,
  payStatusList,
  statusList,
  signatoryList,
  contractSigningStatusList,
  singleOrderMethodList,
  payTermsList,
  currencyList,
  dataList,
  exceptionStatusList,
  afterSalesStatusList
)
</script>

<style lang="less" scoped>
.general-table {
  font-size: 12px !important;
}

:deep(.el-table--default .el-table__cell) {
  padding: 2px 0 !important;
}

:deep(.el-table--default .cell) {
  padding: 0 4px;
}
</style>
